package com.itheima.service;

import com.itheima.domain.Student;
import com.itheima.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentServiceTest {
    private StudentMapper dao;
    private SqlSession sqlSession;

    @Before
    public void init()throws Exception{
        //加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        //获取factory工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //获取sqlsession对象
        sqlSession = factory.openSession();
        //获取dao代理对象
        dao=sqlSession.getMapper(StudentMapper.class);

    }

  @After
  public void destroy()throws IOException{
        //提交事务
      sqlSession.commit();
      //释放资源
      sqlSession.close();
  }

  //需求:延迟加载，懒加载,按需加载
    /*场景模拟:
            1. 使用了学生信息和班级信息, 查询学生和班级表
                System.out.println(student.getName() + "\t" + student.getClasses().getCname());
            2. 只使用了学生信息, 期望只查询学生表
                System.out.println(student.getName());
    需求: 若使用了班级信息, 则查询班级表, 若不使用则不查询. 提升查询效率!!!*/

    @Test
    public void findAll(){
        List<Student> studentList = dao.findAll();
        for (Student student : studentList) {
            System.out.println(student.getName()+"\t所属班级："+student.getClasses().getCname());
           // System.out.println(student.getName());

        }
    }





}
